
import UIKit
import JKSwiftExtension
import AVFoundation
import UniformTypeIdentifiers

enum GlobalQueue {
    static let serial = DispatchQueue(label: "com.SCA.serialQueue", qos: .userInitiated)
    static let dataBase = DispatchQueue(label: "com.SCA.dataBase.serialQueue", qos: .userInitiated)
    static let main = DispatchQueue.main
}

func printf(_ items: Any...) {
    struct Static {
        static let dateFormatter: DateFormatter = {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS"
            if let timeZone = TimeZone(identifier: "Asia/Beijing") {
                formatter.timeZone = timeZone
            }
            return formatter
        }()
    }
    
    let timeString = Static.dateFormatter.string(from: Date())
    let message = items.map { "\($0)" }.joined(separator: " ")
    print("\(timeString) \(message)")
}


func UIFontMake(_ size: CGFloat) -> UIFont {
    return UIFont.systemFont(ofSize: size)
}

func UIFontMediumMake(_ size: CGFloat) -> UIFont {
    return UIFont.systemFont(ofSize: size, weight: .medium)
}

func UIFontSemiboldMake(_ size: CGFloat) -> UIFont {
    return UIFont.systemFont(ofSize: size, weight: .semibold)
}

func UIFontBoldMake(_ size: CGFloat) -> UIFont {
    return UIFont.systemFont(ofSize: size, weight: .bold)
}

func UIColorMake(_ hex: Int) -> UIColor {
    return UIColor(hexInt: hex)
}

func UIColorMake(_ hexString: String) -> UIColor {
    return UIColor.hexStringColor(hexString: hexString)
}

func calculateTextSize(text: String, font: UIFont, maxWidth: CGFloat) -> CGSize {
    let attributes: [NSAttributedString.Key: Any] = [.font: font]
    let rect = text.boundingRect(with: CGSize(width: maxWidth, height: CGFLOAT_MAX),
                                 options: .usesLineFragmentOrigin,
                                 attributes: attributes,
                                 context: nil)
    return CGSizeMake(ceil(rect.size.width), ceil(rect.size.height))
}

func topNavigationController() -> UINavigationController? {
    return topViewController()?.navigationController
}

func topViewController() -> UIViewController? {
    return findTopViewController(from: getMainWindow()?.rootViewController)
}

private  func findTopViewController(from rootVC: UIViewController?) -> UIViewController? {
    guard let rootVC = rootVC else { return nil }
    
    if let presentedVC = rootVC.presentedViewController {
        return findTopViewController(from: presentedVC)
    }
    
    if let tabBarController = rootVC as? UITabBarController {
        return findTopViewController(from: tabBarController.selectedViewController)
    }
    
    if let navController = rootVC as? UINavigationController {
        return findTopViewController(from: navController.topViewController)
    }
    return rootVC
}

func getRootController() -> UIViewController? {
    return getMainWindow()?.rootViewController
}

func getMainWindow() -> UIWindow? {
    if #available(iOS 13.0, *) {
        return UIApplication.shared.windows.first { $0.isKeyWindow }
    } else {
        return UIApplication.shared.keyWindow
    }
}


func getVideoThumbnail(from url: URL, options: [String: Any]? = nil) -> UIImage? {
    let asset = AVURLAsset(url: url, options: options)
    let assetGen = AVAssetImageGenerator(asset: asset)
    assetGen.appliesPreferredTrackTransform = true
    
    let time = CMTime(seconds: 0, preferredTimescale: 600)
    
    do {
        let cgImage = try assetGen.copyCGImage(at: time, actualTime: nil)
        return UIImage(cgImage: cgImage)
    } catch {
        print("获取视频封面失败: \(error.localizedDescription)")
        return nil
    }
}

func makeFilePath(in directory: String, with fileName: String) -> String {
    return (directory as NSString).appendingPathComponent(fileName)
}

func getMimeType(for fileName: String) -> String {
    let pathExtension = (fileName as NSString).pathExtension
    if let type = UTType(filenameExtension: pathExtension),
       let mime = type.preferredMIMEType {
        return mime
    }
    return "application/octet-stream" // 默认值
}

func resizeImage(_ image: UIImage, to size: CGSize, completion: @escaping (UIImage?) -> Void) {
    DispatchQueue.global(qos: .userInitiated).async {
        let renderer = UIGraphicsImageRenderer(size: size)
        let newImage = renderer.image { context in
            image.draw(in: CGRect(origin: .zero, size: size))
        }
        DispatchQueue.main.async {
            completion(newImage)
        }
    }
}

 
func FourCharCodeToString(fourCharCode: FourCharCode) -> String {
    let n = Int(fourCharCode)
    let c1 = Character(UnicodeScalar((n >> 24) & 255)!)
    let c2 = Character(UnicodeScalar((n >> 16) & 255)!)
    let c3 = Character(UnicodeScalar((n >> 8) & 255)!)
    let c4 = Character(UnicodeScalar(n & 255)!)
    return "\(c1)\(c2)\(c3)\(c4)"
}

func convertTimeSecond(_ timeSecond: Int) -> String {
    guard timeSecond >= 0 else {
        return "00:00"
    }
    
    let hours = timeSecond / 3600
    let minutes = (timeSecond % 3600) / 60
    let seconds = timeSecond % 60
    
    if timeSecond < 60 {
        return String(format: "00:%02d", seconds)
    } else if timeSecond < 3600 {
        return String(format: "%02d:%02d", minutes, seconds)
    } else {
        return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
    }
}

func getDescription(_ model: Any) -> String {
    let mirror = Mirror(reflecting: model)
    let typeName = String(describing: type(of: model))
    var propertyPairs: [String] = []
    for child in mirror.children {
        if let label = child.label {
            propertyPairs.append("\(label): \(child.value)")
        }
    }
    
    let result = "\(typeName)(\(propertyPairs.joined(separator: "\n")))"
    return result
}

func printProperties(_ model: Any) {
    print(getDescription(model))
}


 

func fileSize(atPath path: String) -> UInt64 {
    do {
        let attributes = try FileManager.default.attributesOfItem(atPath: path)
        return UInt64((attributes[.size] as? NSNumber)?.int64Value ?? 0)
    } catch {
        print("Failed to get file size: \(error)")
        return 0
    }
}

func formatBytes(_ bytes: Int64) -> String {
    let kb = 1024.0
    let mb = kb * 1024
    let gb = mb * 1024

    let byteCount = Double(bytes)
    let value: Double
    let unit: String

    if byteCount >= gb {
        value = byteCount / gb
        unit = "GB"
    } else if byteCount >= mb {
        value = byteCount / mb
        unit = "MB"
    } else if byteCount >= kb {
        value = byteCount / kb
        unit = "KB"
    } else {
        return "\(Int(byteCount))B" // 字节显示为整数
    }

    let formatter = NumberFormatter()
    formatter.maximumFractionDigits = 1
    formatter.minimumFractionDigits = 1
    formatter.numberStyle = .decimal

    let formatted = formatter.string(from: NSNumber(value: value)) ?? "\(value)"
    return "\(formatted)\(unit)"
}


func ranges(of keyword: String, in text: String) -> [NSRange] {
    guard !keyword.isEmpty else { return [] }

    let pattern = NSRegularExpression.escapedPattern(for: keyword)
    let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive])

    let matches = regex?.matches(in: text, range: NSRange(text.startIndex..., in: text)) ?? []
    return matches.map { $0.range }
}

struct AppEnvironment {
    static var isDebug: Bool {
        #if DEBUG
        return true
        #else
        return false
        #endif
    }
}

//func isValidPassword(_ password: String) -> Bool {
//    // 检查长度和合法字符（不包含中文、空格）
//    let pattern = "^[A-Za-z0-9\\p{P}\\p{S}]{8,20}$"
//    let predicate = NSPredicate(format: "SELF MATCHES %@", pattern)
//    guard predicate.evaluate(with: password) else {
//        return false
//    }
//
//    // 检查是否包含至少一个字母
//    let hasLetter = password.range(of: "[A-Za-z]", options: .regularExpression) != nil
//
//    // 检查是否包含至少一个数字
//    let hasDigit = password.range(of: "[0-9]", options: .regularExpression) != nil
//
//    // 检查是否包含至少一个符号（排除字母和数字）
//    let hasSymbol = password.range(of: "[^A-Za-z0-9]", options: .regularExpression) != nil
//
//    return hasLetter && hasDigit && hasSymbol
//}

func hideMiddleDigits(of phoneNumber: String) -> String {
    guard phoneNumber.count >= 7 else {
        // 手机号长度不足7位，不处理
        return phoneNumber
    }
    
    let start = phoneNumber.prefix(3)
    let end = phoneNumber.suffix(phoneNumber.count - 7)
    return "\(start)****\(end)"
}


func isValidUsername(_ username: String) -> Bool {
    // 至少6个字符，并包含字母和数字
    let regex = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6,}$"
    return NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: username)
}

func isValidPassword(_ password: String) -> Bool {
    // 至少8个字符，并包含字母、数字、特殊字符
    let regex = "^(?=.*[A-Za-z])(?=.*\\d)(?=.*[^A-Za-z\\d])[A-Za-z\\d[^A-Za-z\\d]]{8,}$"
    return NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: password)
}

 
func formatDate(_ isoString: String, dateFormat: String = "yyyy-MM-dd HH:mm:ss") -> String {
    let isoFormatter = ISO8601DateFormatter()
    isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
    
    var date = isoFormatter.date(from: isoString)
    if date == nil {
        isoFormatter.formatOptions = [.withInternetDateTime]
        date = isoFormatter.date(from: isoString)
    }
    
    guard let finalDate = date else { return isoString }
    
    let displayFormatter = DateFormatter()
    displayFormatter.locale = Locale(identifier: "zh_CN")
    displayFormatter.dateFormat = dateFormat
    return displayFormatter.string(from: finalDate)
}


func formatAmount(_ amount: String) -> String {
    guard let value = Double(amount) else { return amount }
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal          // 千分位
    formatter.minimumFractionDigits = 2       // 保留两位小数
    formatter.maximumFractionDigits = 2
    return formatter.string(from: NSNumber(value: value)) ?? amount
}
